#include "element.h"

struct cell * new_cell(thread_t  thread){
	struct cell * cell = malloc(sizeof(struct cell));
	cell->thread = thread;
	cell->next = NULL;
	return cell;
}

struct cell * set_next(struct cell * list, thread_t  thread){
	if (list == NULL) {
		list =  malloc(sizeof(struct cell));
		list->thread = thread;
		list->next = NULL;
		return list; 
	}
	else if ((list->next!= NULL) || (thread == NULL)){
		return E_FAILURE;
	}
	else {
		struct cell * elt = malloc(sizeof(struct cell));
		elt->thread = thread;
		elt->next = NULL;
		list->next = elt;
		return list;
	}
}

int add(struct cell * cell,struct cell *new){
	if (cell->next != NULL){
		cell->next = new;
		return E_SUCCESS;
	}
	else
		return E_FAILURE;
}

int cell_kill(struct cell* cell, int id){
	struct cell* tmp = cell->next;
	struct cell* previous = cell;
	for(tmp = cell->next, previous = cell; tmp != NULL && tmp->thread->id != id && tmp->next != NULL; previous = tmp, tmp = tmp->next);
	if (tmp == NULL || tmp->next == NULL){
		return E_FAILURE;
	}
	else if (tmp->thread->id != id){
		previous->next = tmp->next;
		free(tmp);
		return E_SUCCESS;
	}
	return E_FAILURE;
}

int cell_destroy(struct cell * cell){
	struct cell * tmp;
	for(tmp = cell; cell != NULL; cell = cell->next)
		free(tmp);	
	return E_SUCCESS;
}

void cell_debug(struct cell* cell){
	if(NULL!=cell){
		if(NULL!=cell->thread){
			printf("(%d",cell->thread->id);
			printf(" ,%d)",cell->thread->st);
		}
	}
	else
			printf("vide\n");

}
